﻿using System;
using System.Web;
using System.IO;
using VioletDevelopmentLaboratory.Net.Web.Configuration;

namespace VioletDevelopmentLaboratory.Net.Web.Component
{
	public sealed class MemberImageFileInfo
	{
		private String imageUrl;
		public String ImageUrl { get { return this.imageUrl; } }

		private String physicalFilePath;
		public String PhysicalFilePath { get { return this.physicalFilePath; } }

		private String providerUserKey;
		public String ProviderUserKey { get { return this.providerUserKey; } }

		private MemberImageFileInfo() { }

		public static void Add(HttpPostedFile postedFile, String providerUserKey)
		{
			if (postedFile == null)
				throw new ArgumentNullException("postedFile");

			if (providerUserKey == null)
				throw new ArgumentNullException("providerUserKey");

			if (String.IsNullOrEmpty(providerUserKey))
				throw new ArgumentOutOfRangeException("providerUserKey");

			Remove(providerUserKey);
			String _uniqueFileName = providerUserKey + postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
			String saveFilePath = "";
			getFileManager().Save(postedFile, _uniqueFileName, out saveFilePath);
		}

		private static PhysicalFileManager getFileManager()
		{
			return new PhysicalFileManager(Path.Combine(VUtility.WebApplicationPhysicalPath, VWebConfigurationReader.Path.MemberPictureFolder));
		}

		public static MemberImageFileInfo GetMemberImageFileInfo(String providerUserKey)
		{
			if (providerUserKey == null)
				throw new ArgumentNullException("providerUserKey");

			if (String.IsNullOrEmpty(providerUserKey))
				throw new ArgumentOutOfRangeException("providerUserKey");

			String imageFile = "";
			String[] imageFiles = Directory.GetFiles(getFileManager().SaveFolderPath, providerUserKey + ".*", SearchOption.TopDirectoryOnly);
			Int32 i = 0;
			while (i < imageFiles.Length)
			{
				String _imageFile = imageFiles[i];
				imageFile = Path.GetFileName(_imageFile);
				break;
			}
			MemberImageFileInfo memberImageFileInfo = null;
			if (!String.IsNullOrEmpty(imageFile))
			{
				memberImageFileInfo = new MemberImageFileInfo();
				memberImageFileInfo.providerUserKey = providerUserKey;
				memberImageFileInfo.physicalFilePath = getFileManager().SaveFolderPath + "/" + imageFile;
				memberImageFileInfo.imageUrl = VUtility.GetMemberImageUrl(providerUserKey);
			}
			return memberImageFileInfo;
		}

		public static void Remove(String providerUserKey)
		{
			if (providerUserKey == null)
				throw new ArgumentNullException("providerUserKey");

			if (String.IsNullOrEmpty(providerUserKey))
				throw new ArgumentOutOfRangeException("providerUserKey");

			PhysicalFileManager fileManager = getFileManager();
			foreach (String imageFile in Directory.GetFiles(fileManager.SaveFolderPath, providerUserKey + ".*", SearchOption.TopDirectoryOnly))
			{
				fileManager.Delete(imageFile);
			}
		}
	}
}
